package com.hange.ymcc.service.impl;

import com.hange.ymcc.constant.Regexconstant;
import com.hange.ymcc.exception.BusinessException;
import com.hange.ymcc.exception.ErrorCode;
import com.hange.ymcc.pojo.VerifyCode;
import com.hange.ymcc.service.VerifyCodeService;
import com.hange.ymcc.util.StrUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.concurrent.TimeUnit;

@Service
@Slf4j
public class VerifyCodeServiceImpl implements VerifyCodeService {

    @Autowired
    private RedisTemplate<Object,Object> redisTemplate;
    @Override
    public void SendSmsCode(String mobile) {
        //检验手机号
        if(mobile==null||mobile.length()!=11){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"手机号格式错误");
        }
        //检查redis中是否存在验证码
        String key = String.format(Regexconstant.REDIS_KEY_SMS,mobile);
        VerifyCode verifyCode = (VerifyCode) redisTemplate.opsForValue().get(key);
        String code = null;
        if(verifyCode != null)
        {
            //如果有
            //判断是否60s内
            if( new Date().getTime() - verifyCode.getTimer() < 60*1000)
                throw new BusinessException(ErrorCode.PARAMS_ERROR,"验证码已发送，请60s后重试");
            //3分钟之内发送同一个验证码
            code = verifyCode.getCode();
        }
        else{
            //如果没有，则生成验证码
            code = StrUtils.getRandomString(4);
        }
        long timer = new Date().getTime();
        VerifyCode newVerifyCode = new VerifyCode(code, timer);
        redisTemplate.opsForValue().set(
                key,
                newVerifyCode,
                3,
                TimeUnit.MINUTES
        );
        //发送验证码 todo
        log.info("验证码：{}",code);
    }
}
